package com.ga666666.imagerepo.controller;

import com.ga666666.imagerepo.servce.ImageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: GaoXu
 * @Date: 2022/05/01/14:32
 * @Description:
 */
@RestController
@RequestMapping("image")
public class ImageController {

    @Autowired
    private ImageService imageService;

    @Autowired
    private HttpServletResponse response;

    @PostMapping("upload")
    public String uploadImage(@RequestParam("image") MultipartFile[] images, HttpServletRequest request) {

        String upload = imageService.upload(images, request);

        return upload;
    }

    //http://ga666666.cn/images/20220502035211658.png
    @GetMapping("/images/{imageLink}")
    public void getImage(@PathVariable("imageLink") String imageLink) throws IOException {
        String sufixPhoto = imageLink.split("\\.")[1];
        BufferedImage image = imageService.getImage(imageLink);
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        ImageIO.write(image, sufixPhoto, os);
        response.setContentType("image/" + sufixPhoto);
        OutputStream out = response.getOutputStream();
        out.write(os.toByteArray());
        out.flush();
        os.close();
    }

}
